<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { DriverService, VehicleService, type DriverData, type VehicleData } from '@/services/driverService';

interface Props {
  visible: boolean;
  selectedWaybills: any[];
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'assign', data: { driverId: string; driverPhone: string; vehiclePlate: string }): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 表单数据
const formData = ref({
  driverId: '',
  vehiclePlate: ''
});

// 司机列表
const driverList = ref<DriverData[]>([]);
const vehicleList = ref<VehicleData[]>([]);

// 加载状态
const loading = ref(false);

// 加载司机列表
const loadDrivers = async () => {
  try {
    const result = await DriverService.getAvailableDrivers();
    if (result.success) {
      driverList.value = result.data;
    }
  } catch (error) {
    console.error('加载司机列表失败:', error);
  }
};

// 加载车辆列表
const loadVehicles = async () => {
  try {
    const result = await VehicleService.getAvailableVehicles();
    if (result.success) {
      vehicleList.value = result.data;
    }
  } catch (error) {
    console.error('加载车辆列表失败:', error);
  }
};

// 获取选中司机信息
const selectedDriver = ref<DriverData | null>(null);
const handleDriverChange = (driverId: string) => {
  selectedDriver.value = driverList.value.find(driver => driver.objectId === driverId) || null;
};

// 确认配载
const handleConfirm = () => {
  if (!formData.value.driverId || !formData.value.vehiclePlate) {
    ElMessage.warning('请选择司机和车辆');
    return;
  }

  const assignData = {
    driverId: formData.value.driverId,
    driverPhone: selectedDriver.value?.phone || '',
    vehiclePlate: formData.value.vehiclePlate
  };

  emit('assign', assignData);
  handleClose();
};

// 关闭对话框
const handleClose = () => {
  formData.value = {
    driverId: '',
    vehiclePlate: ''
  };
  selectedDriver.value = null;
  emit('update:visible', false);
};

// 监听对话框显示
const handleOpen = () => {
  loadDrivers();
  loadVehicles();
};

onMounted(() => {
  if (props.visible) {
    handleOpen();
  }
});
</script>

<template>
  <el-dialog
    :model-value="visible"
    title="车辆配载"
    width="600px"
    @update:model-value="emit('update:visible', $event)"
    @open="handleOpen"
    @close="handleClose"
  >
    <div class="assign-dialog">
      <div class="selected-info">
        <h4>选中运单信息</h4>
        <p>已选择 <strong>{{ selectedWaybills.length }}</strong> 个运单进行配载</p>
      </div>

      <el-form :model="formData" label-width="80px">
        <el-form-item label="选择司机" required>
          <el-select
            v-model="formData.driverId"
            placeholder="请选择司机"
            style="width: 100%"
            @change="handleDriverChange"
          >
            <el-option
              v-for="driver in driverList"
              :key="driver.objectId"
              :label="`${driver.driverName} (${driver.phone})`"
              :value="driver.objectId"
            >
              <span style="float: left">{{ driver.driverName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ driver.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择车辆" required>
          <el-select
            v-model="formData.vehiclePlate"
            placeholder="请选择车辆"
            style="width: 100%"
          >
            <el-option
              v-for="vehicle in vehicleList"
              :key="vehicle.objectId"
              :label="`${vehicle.vehicleNumber} (${vehicle.driver})`"
              :value="vehicle.vehicleNumber"
            >
              <span style="float: left">{{ vehicle.vehicleNumber }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ vehicle.driver }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <div v-if="selectedDriver" class="driver-info">
          <h4>司机详细信息</h4>
          <div class="info-grid">
            <div class="info-item">
              <label>姓名：</label>
              <span>{{ selectedDriver.driverName }}</span>
            </div>
            <div class="info-item">
              <label>电话：</label>
              <span>{{ selectedDriver.phone }}</span>
            </div>
            <div class="info-item">
              <label>公司：</label>
              <span>{{ selectedDriver.company }}</span>
            </div>
            <div class="info-item">
              <label>驾照类型：</label>
              <span>{{ selectedDriver.licenseType }}</span>
            </div>
          </div>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading">
          确认配载
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.assign-dialog {
  padding: 20px 0;
}

.selected-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.selected-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.selected-info p {
  margin: 0;
  color: #606266;
}

.driver-info {
  margin-top: 20px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 4px;
}

.driver-info h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.info-item span {
  color: #303133;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-select-dropdown__item) {
  height: auto;
  line-height: 1.5;
  padding: 8px 20px;
}
</style>